package com.example.shirodemo.config.custom;

import com.example.shirodemo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 绫小路
 * @date 2021/1/10 16:58
 * @description
 */
@Component //交给spring托管
public class CustomAuthorizingRealm extends AuthorizingRealm {

  @Autowired
  private UserService userService;

  //授权，每次访问都会授权一次，不缓存会对数据库造成压力
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    System.out.println(principals.toString());
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.setRoles(userService.getRolesByUsername(principals.toString()));
    return info;
  }

  //认证， 账号密码认证 采用 MD5 + 随机盐salt
  //密码加密方式：密码第二位插入盐 再md5加密，例如密码是123，盐是Po*-，那么加盐后是1Po*-23 再md5
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    //因为在controller中做了认证，这里直接返回即可
    return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), this.getName());
  }
}
